package com.hontech.desktoppastacooker.conn

import com.hontech.bv.codec.encodeUint16
import com.hontech.bv.codec.encodeUint8
import com.hontech.desktoppastacooker.conn.frame.Frame
import com.hontech.desktoppastacooker.conn.serial.SerialType
import com.hontech.desktoppastacooker.utils.xorSum


object Proto {
    const val HEAD0 = 0xE1
    const val HEAD1 = 0x1E

    const val HEAD = 0xE11E
    const val END = 0xEF


    const val NOTIFY_LOG = 0
    const val NOTIFY_STATUS = 1


    const val REQ_DOOR_CTRL = 1
    const val REQ_NOZZLE_CTRL = 2
    const val REQ_PARTS_CTRL = 3
    const val REQ_DRAW_HEAT_CTRL = 4
    const val REQ_DRAW_WATER_TEST = 5
    const val REQ_DRAW_TIMEOUT_SET = 6
    const val REQ_HEAT_ARG_SET = 7
    const val REQ_FLOW_SET = 8
    const val QUERY_ARG = 9
    const val REQ_CLEAN = 0x0A
    const val REQ_COOKING = 0x0B
    const val REQ_RF_TRANSLATE = 0x0C
    const val NOTIFY_RF = 0x0D

    const val REQ_OTA_START = 0x0E
    const val REQ_OTA_TRANSLATE = 0x0F
    const val REQ_OTA_COMPLETE = 0x10
    const val REQ_PUMP_ARG_SET = 0x11
    const val REQ_DOOR_ADC_SET = 0x12

    fun makeAck(seq: Int): ByteArray {
        val buf = ByteArray(7)

        encodeUint16(buf, 0, HEAD)
        encodeUint8(buf, 2, 7)
        encodeUint8(buf, 3, Frame.TYPE_ACK)
        encodeUint8(buf, 4, seq)

        val s = buf.xorSum(3, 2)
        encodeUint8(buf, 5, s)
        encodeUint8(buf, 6, END)

        return buf
    }

    fun makeQuery(cmd: Int): ByteArray {

        val buf = ByteArray(7)

        encodeUint16(buf, 0, HEAD)
        encodeUint8(buf, 2, 7)
        encodeUint8(buf, 3, Frame.TYPE_QUERY)
        encodeUint8(buf, 4, cmd)

        val s = buf.xorSum(3, 2)
        encodeUint8(buf, 5, s)
        encodeUint8(buf, 6, END)

        return buf
    }

    fun makeSession(seq: Int): ByteArray {
        val buf = ByteArray(7)

        encodeUint16(buf, 0, HEAD)
        encodeUint8(buf, 2, 7)
        encodeUint8(buf, 3, Frame.TYPE_SESSION)
        encodeUint8(buf, 4, seq)

        val s = buf.xorSum(3, 2)
        encodeUint8(buf, 5, s)
        encodeUint8(buf, 6, END)

        return buf
    }

    fun makeReq(seq: Int, cmd: Int, args: Array<SerialType>): ByteArray {
        var dataLen = 0
        for (arg in args) {
            dataLen += arg.size()
        }
        val len = dataLen + 8
        val buf = ByteArray(len)
        encodeUint16(buf, 0, HEAD)
        encodeUint8(buf, 2, len)
        encodeUint8(buf, 3, Frame.TYPE_REQ)
        encodeUint8(buf, 4, seq)
        encodeUint8(buf, 5, cmd)
        var index = 6
        for (arg in args) {
            arg.encode(buf, index)
            index += arg.size()
        }
        val s = buf.xorSum(3, index - 3)
        encodeUint8(buf, index, s)
        encodeUint8(buf, index + 1, END)
        return buf
    }


}